﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Yuyi.PluginForJS.Addin
{
    public class FoldManager
    {
        private string codeText;
        public FoldManager(string code)
        {
            this.codeText = code;
        }
        public IList<FoldMarker> GetFoldMarkers()
        {
            int line = 1;
            int column = 0;
            IList<FoldMarker> foldMarkers = new List<FoldMarker>();
            Stack<Location> recordHelper = new Stack<Location>();
            for (int i = 0; i < codeText.Length; i++)
            {
                switch (codeText[i])
                {
                    case '\n': line++; column=0; break;
                    case '{': 
                        {
                            column++;
                            recordHelper.Push(new Location(line, column, LocationType.Start));
                        }; break;
                    case '}':
                        {
                            column++;
                            if (recordHelper.Count < 1) continue;
                            Location location;
                            if ((location = recordHelper.Pop()).LocationType == LocationType.Start && recordHelper.Count == 0)
                            {
                                FoldMarker foldMarker = new FoldMarker();
                                foldMarker.StartLine = location.Line;
                                foldMarker.StartColumn = location.Column;
                                foldMarker.EndLine = line;
                                foldMarker.EndColumn = column;
                                foldMarker.IsFolded = true;
                                foldMarkers.Add(foldMarker);
                            }
                        }; break;
                    default: column++; break;
                }
            }
            return foldMarkers;
        }
    }
}
